/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package controlers;

import guiforms.LoginForm;
import guiforms.MainScreen;
import java.util.List;
import java.util.Random;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.Customer;

/**
 *
 * @author Tasos
 * O MainControler einai enas symplirwmatikos controler pou parexei yphresies
 * pou aforoun enegeies pou ginonte stoys Pelates, apotelei symplirwma toy
 * Control Level se oses formes apaitoun stoixeia pelatwn
 */
public class MainControler {
private static EntityManager em1;
private String customerID ="";
private String creditCard;



public MainControler(){
 EntityManagerFactory emf = Persistence.createEntityManagerFactory("SuperMarketPU");
        // Dimiourgia Entity Manager
        em1 = emf.createEntityManager();            
}



//Dimiourgei ena antikeimeno Customer kai prosthetei thn eggrafh toy sthn DB
public void addCustomer(String Address,String Name,String Surname,String creditCard)
{
 //dhmiourgia tyxaiou arithmou kartas me format XXX-XXX
 Random rand = new Random();
 String password = "";
 String firstTriplet = Integer.toString(rand.nextInt(900) + 100);
 String secondTriplet = Integer.toString(rand.nextInt(900) + 100);
 String cardNum = firstTriplet+"-"+secondTriplet;
 //Instanciate ena Customer Objecy
 Customer tempCust = new Customer(0,Name,Surname,cardNum,0);
 //enhmerwsh twn stoixeiwn toy
 tempCust.setAddress(Address);
 tempCust.setCreditcard(creditCard);
//Enhmerwsh toy Password, ginetai se ksexwristo Dialog gia asfaleia,
//o Kwdikos exei periorismo !null kai katw orio 4 xarakthrwn
while(password != null && password.length()<4)
{
password = (String)JOptionPane.showInputDialog(new JFrame("Password"),"Δωστε επιθυμητο κωδικό πρόσβασης",JOptionPane.NO_OPTION);
if(password == null)
return;
}

//Enhmerwsh toy antikeimenou Customer me to password
tempCust.setPassword(password);
//Eisagwgh srhn DB
em1.getTransaction().begin();
em1.persist(tempCust);
em1.getTransaction().commit();
}


//Enhmerwnei mia yparxousa eggrafh ths Db analoga me ta stoixeia pou dinontai
public boolean updateCustomer(String cardNumber,String Address,String Name,String Surname,String creditCard){
    //fetch and Create Object    
    Customer c = findCustomerByCard(cardNumber);             
    //An vrethike h eggrafh    
    if (c!=null){                                  
            em1.getTransaction().begin();
            try { //prospathia enhmerwseis twn pediwn
                c.setAddress(Address);
                c.setFirstName(Name);
                c.setLastName(Surname);
                c.setCreditcard(creditCard);
                em1.getTransaction().commit(); 
                return true;
            } catch (Exception e) { //Catch apotyxias eggrafhs
                em1.getTransaction().rollback();
                return false;
            }            
        }
return false;    
}

//Methodos gia enhmerwsh toy PAssword enos pelath
//To password exei ksexwristh methodo update gia logous asfaleias
//h diadikasia einai h idia me thn updateCustomer pio panw
public boolean updatePassword(String cardNumber,String password){
        Customer c = findCustomerByCard(cardNumber);             
        if (c!=null){                                  
            em1.getTransaction().begin();
            try {
                c.setPassword(password);
                em1.merge(c);
                em1.getTransaction().commit();
                return true;
            } catch (Exception e) {
                em1.getTransaction().rollback();
                return false;
            }            
        }
return false;    
}

//Methodos pou afairei thn eggrafh enos pelath apo thn DB
public boolean removeCustomer(String cardNumber){
    //Dimiourgia antikeimenou     
    Customer c = findCustomerByCard(cardNumber); //fetch Customer            
        if (c!=null){                                  
            em1.getTransaction().begin();
            try {
                em1.remove(c); //remove
                em1.getTransaction().commit();
                return true;
            } catch (Exception e) { //Catch apotyxias
                em1.getTransaction().rollback();
                return false;
            }            
        }
return false;    
}


//Methodos h opoia epistrefei ena Customer Obj analoga me to User-ID toy
    public Customer findCustomerByCard(String CardNumber){       
        //Dimiourgia toy Query
        TypedQuery<Customer> findCustomerQuery = em1.createNamedQuery("Customer.findByPointsCardNumber", Customer.class);
        findCustomerQuery.setParameter("pointsCardNumber", CardNumber);
        //apothikeysh results
        List<Customer> customerResults = findCustomerQuery.getResultList();      
        //Elegxos gia monadiko apotelesma (Edw einai anagaio mias kai to random creation toy
        //User-ID den eggyatai monadikothta User-IDs
        if (customerResults.size() != 1){            
            return null;
        }
        else {
            Customer c = customerResults.get(0);  
            return c;
        }        
    }

}
